#coding:utf-8
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext
from django.core.serializers import get_serializer
import pickle
import json
# models
from api.models import Record
from api.models import Account
from api.models import Group
###################################################################
# util
def load_record():
	with open( 'record.data' , 'rb' ) as recordFile:
		return( pickle.load(recordFile) )
# json 序列化 util
JSONSerializer = get_serializer("json")
serializer = JSONSerializer()
###################################################################
def load_records_to_db(request):
	L = load_record()
	for item in L[1:]:
		Record.objects.get_or_create(NAME=item['type'] ,TIME=int( item['time'].timestamp() ) * 1000,PRICE=item['price'],GROUP=item['group'])
	return HttpResponse( 'success' )

def list(request , tableName):
	print( tableName )
	tables = {
		'Record' : Record,
		'Account' : Account,
		'Group' : Group,
	}

	allResult = tables[tableName].objects.all()
	resp = serializer.serialize(allResult)
	return HttpResponse( resp )

# def list_record(request):

# 	all = Record.objects.all()
# 	groups = all.values('GROUP').distinct()
# 	resp = { 'result' : serializer.serialize(all) , 'groups' : list( groups ) }
# 	response = json.dumps( resp )
# 	return HttpResponse( response )

def add_account(request):

	Account.objects.get_or_create( name = request.POST['name'] ,time=request.POST['time'] , price = request.POST['price'] ,group = request.POST['group'])
	return HttpResponse('success')

def add(request ,tableName):
	if tableName=='Group':
		name = request.POST.get('name')
		item = request.POST.get('item')
		Group.objects.update_or_create( name=name ,item = item )

		return HttpResponse('success')
	if tableName=='Account':
		name = request.POST.get('name')
		time = request.POST.get('time')
		price = request.POST.get('price')
		group = request.POST.get('group')

		Account.objects.update_or_create(name = name , time = time, price = price , group  = group)
		return HttpResponse('success')

